package com.example.demo.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//解析和验证JWT令牌的工具类
@Component
public class JwtTokenUtil {
    //token的过期时间
    public static final long JWT_TOKEN_VALIDITY = 5*60*60*1000;

    //TOKEN的秘钥
    @Value("${jwt.secret}")
    private String secret;

    //从Token中获得Claims
    public Claims getClaimFromToken(String token){
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token).getBody();
    }

    //生成Token
    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims = new HashMap<>();
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(userDetails.getUsername())
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis()+JWT_TOKEN_VALIDITY))
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    //对Token进行验证(即验证Claims)
    public Boolean validateToken(String token,UserDetails userDetails){
        return validateClaim(getClaimFromToken(token),userDetails);
    }

    //对Claims进行验证
    public boolean validateClaim(Claims claim,UserDetails userDetails){
        //可以验证其他信息，如角色
        return userDetails != null &&
                claim.getSubject().equals(userDetails.getUsername())
                && !claim.getExpiration().before(new Date());
    }

    public Boolean canTokenBeRefreshed(String token){
        return(!isTokenExpired(token) || ignoreTokenExpiration(token));
    }

    public Boolean isTokenExpired(String token){
        Claims claims = getClaimFromToken(token);
        return claims.getExpiration().before(new Date());
    }

    private Boolean ignoreTokenExpiration(String token){
        return false;
    }
}
